<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="菜单分类ID" prop="categoryId">
        <el-input
          v-model="queryParams.categoryId"
          placeholder="请输入菜单分类ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布时间" prop="publishTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.publishTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择发布时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="发布状态" prop="publishStatus">
        <el-select v-model="queryParams.publishStatus" placeholder="请选择发布状态" clearable size="small">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input
          v-model="queryParams.sort"
          placeholder="请输入排序"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="热门标识" prop="hotFlag">
        <el-input
          v-model="queryParams.hotFlag"
          placeholder="请输入热门标识(0-非热门 1-热门)"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最新标识" prop="newFlag">
        <el-input
          v-model="queryParams.newFlag"
          placeholder="请输入最新标识(0-非最新 1-最新)"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文章类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择文章类型" clearable size="small">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:article:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:article:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:article:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:article:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border stripe v-loading="loading" max-height="650" :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column fixed type="selection" width="55" align="center" />
      <template v-for="(item, index) in articleHeadList">
        <el-table-column
          align="center"
          show-overflow-tooltip
          :key="index"
          :label="item.label"
          :prop="item.prop"
          :width="handleColumnWidth(item.label)"
        >
          <template slot-scope="scope">
            <el-image
              v-if="item.prop === 'coverImage'"
              style="height: 50px; width: 50px"
              :src="scope.row.coverImage"
              :preview-src-list="srcList"
            >
            </el-image>
            <span v-else-if="item.prop === 'status'" v-text="scope.row.status === 0 ? '正常' : scope.row.status === 1 ? '异常' : ''"></span>
            <span v-else-if="item.prop === 'hotFlag'" v-text="scope.row.hotFlag === 0 ? '非热门' : scope.row.hotFlag === 1 ? '热门' : ''"></span>
            <span v-else-if="item.prop === 'newFlag'" v-text="scope.row.newFlag === 0 ? '非最新' : scope.row.newFlag === 1 ? '最新' : ''"></span>
            <span v-else-if="item.prop === 'publishStatus'" v-text="scope.row.publishStatus === 0 ? '已发布' : scope.row.publishStatus === 1 ? '未发布' : ''"></span>
            <span
              style="cursor: pointer;"
              v-else-if="item.prop === 'link'"
              v-text="scope.row.link"
              @click="handleCopyLink(scope.row)">
            </span>
            <template v-else>{{ scope.row[scope.column.property] }}</template>
          </template>
        </el-table-column>
      </template>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:article:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:article:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="40%" append-to-body>
      <el-form ref="form" :disabled="disabled" :model="form" :rules="rules" label-width="180px" label-position="top">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="form.path" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="菜单分类ID" prop="categoryId">
          <el-input v-model="form.categoryId" placeholder="请输入菜单分类ID" />
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker clearable size="small"
            v-model="form.publishTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择发布时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发布状态">
          <el-radio-group v-model="form.publishStatus">
            <el-radio label="0">已发布</el-radio>
            <el-radio label="1">未发布</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="热门标识(0-非热门 1-热门)" prop="hotFlag">
          <el-input v-model="form.hotFlag" placeholder="请输入热门标识(0-非热门 1-热门)" />
        </el-form-item>
        <el-form-item label="最新标识(0-非最新 1-最新)" prop="newFlag">
          <el-input v-model="form.newFlag" placeholder="请输入最新标识(0-非最新 1-最新)" />
        </el-form-item>
        <el-form-item label="摘要" prop="summary">
          <el-input v-model="form.summary" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="内容">
          <editor v-if="update" :read-only="readOnly" v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="关键词" prop="keywords">
          <el-input v-model="form.keywords" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="封面图片">
          <imageUpload v-model="form.coverImage"/>
        </el-form-item>
        <el-form-item label="来源" prop="origin">
          <el-input v-model="form.origin" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="外部链接" prop="link">
          <el-input v-model="form.link" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="文章类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择文章类型">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listArticle, getArticle, delArticle, addArticle, updateArticle, exportArticle } from "@/api/system/article";
import { listHead } from "@/api/system/head";
import ImageUpload from '@/components/ImageUpload';
import Editor from '@/components/Editor';

export default {
  name: "Article",
  components: {
    ImageUpload,
    Editor,
  },
  data() {
    return {
      // 表头数据
      articleHeadList: [],
      // 预览大图
      srcList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      articleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        path: null,
        categoryId: null,
        publishTime: null,
        publishStatus: null,
        sort: null,
        hotFlag: null,
        newFlag: null,
        summary: null,
        content: null,
        keywords: null,
        coverImage: null,
        origin: null,
        link: null,
        type: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 表单禁用
      disabled: false,
      // 富文本只读
      readOnly: false,
      // 组件刷新
      update: true,
    };
  },
  created() {
    this.getList();
    this.getArticleHeadList()
  },
  methods: {
    /** 内容【表头】列表 */
    getArticleHeadList() {
      listHead({bid: 'sys_article'}).then(response => {
        const listArr = []
        response.rows.forEach(params =>{
          listArr.push({
            id: params.id,
            label: params.dictName,
            prop: this.toHump(params.dictType)
          })
        })
        this.articleHeadList = listArr
      })
    },
    /** 复制功能 */
    handleCopyLink(row) {
      let _this = this;
      this.$copyText(row.link).then(function (e) {
        _this.$message({
          showClose: true,
          message: "复制成功",
          type: "success"
        });
      }, function (e) {
        _this.$message({
          showClose: true,
          message: "复制失败，请手动复制",
          type: "error"
        });
      })
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listArticle(this.queryParams).then(response => {
        const listArray = []
        response.rows.forEach(params => {
          listArray.push(params.coverImage)
        })
        this.srcList = listArray
        this.articleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        path: null,
        categoryId: null,
        publishTime: null,
        publishStatus: 0,
        sort: null,
        hotFlag: null,
        newFlag: null,
        summary: null,
        content: null,
        keywords: null,
        coverImage: null,
        origin: null,
        link: null,
        type: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        status: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加【请填写功能名称】";
    },
    /** 查看详情按钮 */
    handleView(row) {
      this.reset();
      this.readOnly = true
      // 移除组件
      this.update = false
      // 在组件移除后，重新渲染组件
      // this.$nextTick可实现在DOM 状态更新后，执行传入的方法。
      this.$nextTick(() => {
        this.update = true
      })
      const id = row.id || this.ids
      getArticle(id).then(response => {
        this.disabled = true
        this.form = response.data;
        this.open = true;
        this.title = "查看详情";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.readOnly = false
      this.reset();
      const id = row.id || this.ids
      // 移除组件
      this.update = false
      // 在组件移除后，重新渲染组件
      // this.$nextTick可实现在DOM 状态更新后，执行传入的方法。
      this.$nextTick(() => {
        this.update = true
      })
      getArticle(id).then(response => {
        this.disabled = false
        this.form = response.data;
        this.open = true;
        this.title = "修改【请填写功能名称】";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateArticle(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addArticle(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delArticle(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有【请填写功能名称】数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportArticle(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 自定义表头宽度 */
    handleColumnWidth(str) {
      let columnWidth = 0;
      for (let char of str) {
        if ((char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z')) {
          // 如果是英文字符，为字符分配10个单位宽度，单位宽度可根据字体大小调整
          columnWidth += 10
        } else if (char >= '\u4e00' && char <= '\u9fa5') {
          // 如果是中文字符，为字符分配14个单位宽度，单位宽度可根据字体大小调整
          columnWidth += 14
        } else {
          // 其他种类字符，为字符分配10个单位宽度，单位宽度可根据字体大小调整
          columnWidth += 10
        }
      }
      if (columnWidth < 120) {
        // 设置最小宽度
        columnWidth = 120
      }
      return columnWidth + 'px'
    }
  }
};
</script>

<style scoped lang="scss">
</style>
